#!/usr/bin/env bash
set -x

# Test that with sops.strict=false, mise continues when age key is not available

mise use sops age

# Create an encrypted file but don't set age key
age="$(mise x -- age-keygen 2>&1)"
age_pub="$(echo "$age" | grep "# public key:" | awk '{print $4}')"

# json test with strict=false
echo '{ "SECRET": "mysecret" }' >.env.json
mise x -- sops encrypt -i --age "$age_pub" .env.json

# Set non-strict mode
mise settings set sops.strict false

# Clear age key to simulate missing key
export MISE_SOPS_AGE_KEY=
rm -f ~/.config/mise/age.txt

# Should continue without failing and not include the secret
assert "mise set _.file=.env.json"
# The env should not contain the decrypted secret since key is missing
assert_not_contains "mise env" "export SECRET=mysecret"

# Test with strict=true (default behavior)
mise settings set sops.strict true

# This should fail
assert_fail "mise env"

# Test with yaml files too
# Clean up previous encrypted files to avoid interference
rm -f .env.json .env.yaml
# Temporarily clear file config to avoid decryption issues
mise settings unset _.file
mise x -- age-keygen -o ~/age.txt
age_pub="$(grep "# public key:" ~/age.txt | awk '{print $4}')"
echo 'SECRET: mysecret' >.env.yaml
mise x -- sops encrypt -i --age "$age_pub" .env.yaml

# Remove the key file
rm -f ~/age.txt
export MISE_SOPS_AGE_KEY=

# Set non-strict mode
mise settings set sops.strict false

# Should work with non-strict mode
assert "mise set _.file=.env.yaml"
assert_not_contains "mise env" "export SECRET=mysecret"

# Reset to strict mode and verify it fails
mise settings set sops.strict true
assert_fail "mise env"
